package com.psq.core.common.network.interceptor

import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ToastUtils
import com.psq.core.common.provider.IMainProvider
import com.psq.core.common.provider.IUserInfoProvider
import com.psq.core.common.provider.ROUTER_LOGIN_PROVIDER
import com.psq.core.common.provider.ROUTER_MAIN_PROVIDER
import com.psq.core.common.provider.ROUTER_USER_INFO_PROVIDER
import com.psq.core.common.provider.*
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.IOException

/**
 * 日志拦截器
 */
class LoggingInterceptor : Interceptor {

    companion object {
        private const val TAG = "LoggingInterceptor"
    }

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val t1 = System.nanoTime()
        Log.v(
            TAG, String.format(
                "发送请求 %s on %s%n%s",
                request.url, request.method, request.headers
            )
        )

        val response = chain.proceed(request)

        val t2 = System.nanoTime()
        val responseBody: ResponseBody = response.peekBody((1024 * 1024).toLong())


        val responseBodyString = responseBody.string()

        Log.v(
            TAG,
            String.format(
                "接收响应: [%s] %n返回json:【%s】 %.1fms%n%s",
                response.request.url,
                responseBodyString,
                (t2 - t1) / 1e6,
                response.headers
            )
        )
        errorDispose(responseBodyString)
        return response
    }

    /**
     * 结果返回异常处理
     */
    private fun errorDispose(responseBody: String) {
        if (responseBody.isEmpty()) {
            return
        }
        val jsonObject = JSONObject(responseBody)
        val errorCode = jsonObject.optString("errorCode")
        if (errorCode == "403") {

            (ARouter.getInstance().build(ROUTER_USER_INFO_PROVIDER)
                .navigation() as IUserInfoProvider).logout()
            val mainProvider =
                ARouter.getInstance().build(ROUTER_MAIN_PROVIDER).navigation() as IMainProvider

            val loginProvider = ARouter.getInstance().build(ROUTER_LOGIN_PROVIDER)
                .navigation() as ILoginProvider
            //不是主界面 并且不是登录模块 跳转到主界面并且打开登录
            if (mainProvider.getClassName() != ActivityUtils.getTopActivity()::class.java.name
                && !loginProvider.activityIsLoginModule(ActivityUtils.getTopActivity())
            ) {
                mainProvider.navHome()
                loginProvider.navLogin()
            }
            ToastUtils.showShort("登录已过期请重新登录")
        }
    }

}